/* ==================================================================   
 * Created [2009-4-27 下午11:32:55] by Jon.King 
 * ==================================================================  
 * TSS 
 * ================================================================== 
 * mailTo:jinpujun@hotmail.com
 * Copyright (c) Jon.King, 2009-2012 
 * ================================================================== 
*/

package com.jinhe.tss.core.cachepool.extend.connection.datasource;

import java.sql.Connection;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.hibernate.cfg.Environment;
import org.hibernate.util.NamingHelper;

import com.jinhe.tss.core.exception.BusinessException;

/**
 * <p>
 * DatasourceConnectionProvider.java
 * </p>
 * 
 *  ## JNDI Datasource

    #hibernate.connection.datasource jdbc/tss
    #hibernate.connection.username db2
    #hibernate.connection.password db2
 * 
 * @author Jon.King 2007-5-9
 */
class DatasourceConnectionProvider implements IConnectionProvider{
    
    private static final Logger log = Logger.getLogger(DatasourceConnectionProvider.class);
    
    public Connection getConnection(Properties p){
        try {
            String jndiName = p.getProperty(Environment.DATASOURCE);

            DataSource ds = (DataSource) NamingHelper.getInitialContext(p).lookup(jndiName);
            if (ds == null) {
                throw new BusinessException("Could not find datasource: " + jndiName);
            }
            
            String user = p.getProperty(Environment.USER);
            String pass = p.getProperty(Environment.PASS);
            
            return user != null || pass != null ? ds.getConnection(user, pass) : ds.getConnection();
        } catch (Exception e) {
            log.fatal("从数据源获取连接时出错", e);
            throw new BusinessException("从数据源获取连接时出错", e);
        }
    }
}
